import {
    ADDCART,
    CHANGE_SELECT,
    NUM_CHANGE,
    SELECT_CHANGE,
    SELECT_ALL,
    PULATE
} from './contant'

export default {
    [ADDCART](state, carts) {
        state.cart.push(carts)
        localStorage.cart = JSON.stringify(state.cart)
    },
    // 头部当行文字切换 编辑、完成
    [CHANGE_SELECT](state, select) {
        if(select) {
            state.text = '完成'
            state.subtext = '删除'
        }else {
            state.text = '编辑'
            state.subtext = '下单'
        }
    },
    // 数量更改、计算总计
    [NUM_CHANGE](state, keyword) {
        switch(keyword.key) {
          case 'plus':
              state.cart.forEach(cart=> {
                  if(cart.name == keyword.name) {
                      cart.num++
                  }
              })
              break;
          case 'minus':
            state.cart.forEach(cart=> {
                if(cart.name == keyword.name) {
                    if(cart.num <= 1) {
                        cart.num = 1
                    }else {
                        cart.num--;
                    }
                }
            })
              break;
        }
        state.total = 0
        state.cart.forEach(cart=> {
          if(cart.checked) {
            state.total += cart.num * cart.price;
          }
        })
        localStorage.cart = JSON.stringify(state.cart)
    },
    // 单个商品选中、计算总价
    [SELECT_CHANGE](state, name) {
        state.cart.forEach(cart=> {
            if(cart.name == name.name) {
                cart.checked = name.checked
            }
        })
        // 全部选中全选高亮
        state.checkedAll = state.cart.every(item=> {
          return item.checked == true
        })
        state.total = 0
        state.cart.forEach(cart=> {
          if(cart.checked) {
            state.total += cart.num * cart.price;
          }
        })
        localStorage.cart = JSON.stringify(state.cart)
    },
    // 全部商品选中、计算总价
    [SELECT_ALL](state, checked) {
        state.checkedAll = checked;
        state.cart.forEach(item=> {
          item.checked = state.checkedAll
        })
        state.total = 0
        state.cart.forEach(cart=> {
          if(cart.checked) {
            state.total += cart.num * cart.price;
          }
        })
        localStorage.cart = JSON.stringify(state.cart)
    },
    // 操作商品 删除、下单
    [PULATE](state) {
        if(state.subtext == '删除') { // 批量删除
          for(var i=state.cart.length-1;i>=0;i--){
                if(state.cart[i].checked){
                    var index=state.cart.indexOf(state.cart[i]);
                    state.cart.splice(index,1);
                }
            }
            state.total = 0
            state.cart.forEach(cart=> {
              if(cart.checked) {
                state.total += cart.num * cart.price;
              }
            })
            localStorage.cart = JSON.stringify(state.cart)
        }else {
          return
        }
    }
}